package com.authine.cloudpivot.ext.controller;

import com.authine.cloudpivot.engine.api.facade.OrganizationFacade;
import com.authine.cloudpivot.engine.api.model.organization.DepartmentModel;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectQueryModel;
import com.authine.cloudpivot.engine.api.model.runtime.SelectionValue;
import com.authine.cloudpivot.engine.component.query.api.FilterExpression;
import com.authine.cloudpivot.engine.component.query.api.Page;
import com.authine.cloudpivot.engine.component.query.api.helper.PageableImpl;
import com.authine.cloudpivot.engine.component.query.api.helper.Q;
import com.authine.cloudpivot.engine.enums.status.SequenceStatus;
import com.authine.cloudpivot.engine.enums.type.UnitType;
import com.authine.cloudpivot.ext.doman.ItemInfo;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import com.authine.cloudpivot.web.api.dubbo.DubboConfigService;
import com.authine.cloudpivot.web.api.helper.oraganization.UserHelper;
import com.authine.cloudpivot.web.api.util.AuthUtils;
import com.authine.cloudpivot.web.api.view.ResponseResult;
import com.authine.cloudpivot.web.api.view.organization.UserManagerVO;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: brookpeng
 * @Date: 2022/2/15 20:44
 */
@Slf4j
@RestController
@RequestMapping("/api/coursePreview")
public class CoursePreviewController extends BaseController {

    @PersistenceContext
    EntityManager entityManager;

    @Autowired
    private DubboConfigService dubboConfigService;

    @Autowired
    private HomePagesContoller homePagesContoller;

    /**
     * 课程预览申请
     *
     * @param courseId
     * @return
     */
    @GetMapping("application")
    @Transactional
    public ResponseResult application(@RequestParam String courseId) {

        String userId = AuthUtils.getUserId();
        String coursePreviewTable = getBizObjectFacade().getTableName("coursePreview");
        StringBuilder sql = new StringBuilder(
                "SELECT\n" +
                        "\tT1.kcqd,\n" +
                        "\tT2.state\n" +
                        "FROM\n" +
                        "\t`" + coursePreviewTable + "` T1\n" +
                        "INNER JOIN `biz_workflow_instance` T2 ON T1.id = T2.bizObjectId\n" +
                        "WHERE\n" +
                        "\tT1.ShortText_kcbh = '" + courseId + "'\n" +
                        "AND T1.creater = '" + userId + "'\n" +
                        "AND (\n" +
                        "\tT2.state = 'PROCESSING'\n" +
                        "\tOR T2.state = 'COMPLETED'\n" +
                        ");");
        List<Map<String, Object>> resultList = entityManager.createNativeQuery(sql.toString()).getResultList();

        if (CollectionUtils.isNotEmpty(resultList)) {
            return getOkResponseResult("该课程已申请预览", "success");
        }

        BizObjectQueryModel queryModel = new BizObjectQueryModel();
        queryModel.setSchemaCode("kcqd");
        queryModel.setQueryCode("kcqd");
        queryModel.setPageable(new PageableImpl(0, 20));

        FilterExpression.Item it = Q.it("kcbh", FilterExpression.Op.Eq, courseId);

        queryModel.setFilterExpr(it);

        Page<BizObjectModel> page = getBizObjectFacade().queryBizObjects(queryModel);

        BizObjectModel courseInfoModel;
        if (page.getTotal() == 0) {
            log.info("\n=======================课程编号：" + courseId + "在入库课程清单中不存在");
            return getErrResponseResult(500L, "课程编号：" + courseId + "在入库课程清单中不存在");
        } else {
            courseInfoModel = page.getContent().get(0);
        }

        // 课程名称
        String courseName = MapUtils.getString(courseInfoModel.getData(), "courseName");
        // 数据id
        String id = MapUtils.getString(courseInfoModel.getData(), "id");

        Map<String, Object> map = new HashMap<>();

        map.put("kcqd", courseName);
        map.put("ShortText_kcbh", courseId);
        map.put("pfzt", "同意");

        BizObjectCreatedModel coursePreview = new BizObjectCreatedModel("coursePreview", map, false);

        String bizObjectId = getBizObjectFacade().saveBizObject(userId, coursePreview, false);

        UserModel user = getOrganizationFacade().getUser(userId);

        String instanceId = getWorkflowInstanceFacade().startWorkflowInstance(user.getDepartmentId(), userId, "coursePreview", bizObjectId, true);

        String kcqdTable = getBizObjectFacade().getTableName("kcqd");
        StringBuilder kcqdSelect = new StringBuilder("select T.sqkcrc from `" + kcqdTable + "` T where T.id = '" + id + "';");
        BigDecimal sqkcrcNum = (BigDecimal) entityManager.createNativeQuery(kcqdSelect.toString()).getSingleResult();

        StringBuilder kcqdUpdate;
        if (sqkcrcNum == null) {
            kcqdUpdate = new StringBuilder("update `" + kcqdTable + "` T set T.sqkcrc = '1' where T.id = '" + id + "';");
        } else {
            kcqdUpdate = new StringBuilder("update `" + kcqdTable + "` T set T.sqkcrc = T.sqkcrc + 1 where T.id = '" + id + "';");
        }
        int updateNum = entityManager.createNativeQuery(kcqdUpdate.toString()).executeUpdate();

        log.info("\n=======课程预览申请流程发起成功,instanceId={}", instanceId);
        if (updateNum != 0) {
            log.info("\n=======增加课程申请次数记录成功,instanceId={}", updateNum);
        }

        return getOkResponseResult("课程预览申请流程发起成功", "success");
    }

    /**
     * 课程浏览权限check
     *
     * @param courseId
     * @return
     */
    @GetMapping("checkPreview")
    public ResponseResult<Boolean> checkPreview(@RequestParam String courseId) {

        boolean preview = false;
        String passString = "全部";

        String kcqdTableName = getBizObjectFacade().getTableName("kcqd");
        StringBuilder selectCourseInfo = new StringBuilder("SELECT * FROM `" + kcqdTableName + "` T WHERE T.id = '" + courseId + "';");
        List<Map<String, Object>> courseInfo = entityManager.createNativeQuery(selectCourseInfo.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
        String previewArea = (String) courseInfo.get(0).get("previewArea");
        String checkKcbh = (String) courseInfo.get(0).get("kcbh");
        OrganizationFacade organizationFacade = getOrganizationFacade();
        String userId = getUserId();
        if (StringUtils.isEmpty(previewArea) || passString.equals(previewArea)) {
            // 范围未设定
            preview = true;
        } else {
            //2020-05-08
            //第一种情况，用户直接存在于 StaffDeptMix(综合范围选择) 混合选人控件选择的人员中，可直接把用户id作为搜索条件
            //第二种情况，用户的部门存在于 StaffDeptMix(综合范围选择) 混合选人控件选择的部门中
            //①获取登录用户的所有部门id
            List<String> departmentIds = new ArrayList<>();
            List<DepartmentModel> departmentsByUserId = organizationFacade.getDepartmentsByUserId(userId);
            for (DepartmentModel departmentModel : departmentsByUserId) {
                homePagesContoller.getAllParentDepartmentIds(departmentModel.getId(), departmentIds);
            }
            log.info("登录用户的本级+上级部门id集合:{}", departmentIds);
            log.info("登录用户的本级+上级部门id集合元素个数:{}", departmentIds);
            //②将用户的id存入departmentIds，下面有用
            departmentIds.add(userId);
            String departmentIdsSql = "'";
            for (int i = 0; i < departmentIds.size(); i++) {
                if (i != departmentIds.size() - 1) {
                    departmentIdsSql = departmentIdsSql + departmentIds.get(i) + "|";
                } else {
                    departmentIdsSql = departmentIdsSql + departmentIds.get(i);
                }
            }
            departmentIdsSql = departmentIdsSql + "'";
            log.info("departmentIdsSql:{}", departmentIdsSql);

            String selectSql = "select * from " + kcqdTableName + " where id = '" + courseId + "' and StaffDeptMix regexp " + departmentIdsSql;
            List<Map<String, Object>> selectSqlResult = entityManager.createNativeQuery(selectSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
            preview = selectSqlResult.size() > 0 ? true : false;

            //String kkffw = (String) courseInfo.get(0).get("StaffDeptMix");
            //if (StringUtils.isEmpty(kkffw)) {
            //    // 范围未设定
            //    return getOkResponseResult(true, "success");
            //}
            //StringBuilder makeJson = new StringBuilder("{\"StaffDeptMix\":");
            //makeJson.append(kkffw);
            //makeJson.append("}");
            //JSONObject jsonObject = JSONObject.fromObject(makeJson.toString());
            //JSONArray jsonList = jsonObject.getJSONArray("StaffDeptMix");
            //int size = jsonList.size();
            //String loginUserId = getUserId();
            //for (int i = 0; i < size; i++) {
            //    JSONObject kkffwObject = jsonList.getJSONObject(i);
            //
            //    // 判断混合选人项目是1.部门，2.角色，3.用户
            //    int type = (Integer) kkffwObject.getInt("type");
            //
            //    if (3 == type) {
            //        String id = (String) kkffwObject.get("id");
            //        if (StringUtils.isNotEmpty(id) && StringUtils.isNotEmpty(loginUserId) && id.equals(loginUserId)) {
            //            preview = true;
            //            break;
            //        }
            //    }
            //
            //    if (1 == type) {
            //        String id = (String) kkffwObject.get("id");
            //        DepartmentModel department = getOrganizationFacade().getDepartment(id);
            //        if (department == null) {
            //            continue;
            //        }
            //        String courseAreaCode = department.getQueryCode();
            //        String userId = getUserId();
            //        List<DepartmentModel> departmentsInfo = getOrganizationFacade().getDepartmentsByUserId(userId);
            //        boolean allow = false;
            //        for (DepartmentModel departmentModel : departmentsInfo) {
            //            String sourceId = departmentModel.getSourceId();
            //            if (courseAreaCode.contains(sourceId)) {
            //                preview = true;
            //                allow = true;
            //                break;
            //            }
            //        }
            //        if (allow) {
            //            break;
            //        }
            //    }
            //}
        }

        if (!preview) {
            // 判断是否申请过开课并审批通过
            StringBuilder passCourseListSql = new StringBuilder();
            String coursePreviewTableName = getBizObjectFacade().getTableName("coursePreview");
            passCourseListSql.append("SELECT T2.ShortText_kcbh AS kcbh FROM `biz_workflow_instance` T1 INNER JOIN `" + coursePreviewTableName + "` T2 ON T1.bizObjectId = T2.id WHERE T1.schemaCode = 'coursePreview' AND T1.workflowCode = 'coursePreview' AND T1.state = 'COMPLETED' AND T1.originator = '" + getUserId() + "' AND T2.pfzt = '同意';");
            List<Map<String, Object>> passCourseKcbhList = entityManager.createNativeQuery(passCourseListSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
            for (Map<String, Object> stringObjectMap : passCourseKcbhList) {
                String kcbh = MapUtils.getString(stringObjectMap, "kcbh", "");
                if (kcbh.equals(checkKcbh)) {
                    preview = true;
                    break;
                }
            }
        }

//#############################2022-05-08  首先获取该用户的可见活动范围，再判断courseId代表的课程是否存在于课程范围
        ResponseResult<List<Map<String, Object>>> listResponseResult = homePagesContoller.rollMessage();
        List<Map<String, Object>> data = listResponseResult.getData();
        if (data.size() > 0 && !preview) {
            //获取到用户可见的活动的表单id集合
            List<String> idList = data.stream().map(a -> (String) a.get("id")).collect(Collectors.toList());
            String idListSql = "(";
            for (int i = 0; i < idList.size(); i++) {
                if (i != idList.size() - 1) {
                    idListSql = idListSql + "'" + idList.get(i) + "',";
                } else {
                    idListSql = idListSql + "'" + idList.get(i) + "'";
                }
            }
            idListSql = idListSql + ")";
            StringBuilder selectSql = new StringBuilder();
            String xxtsglTableName = getBizObjectFacade().getTableName("xxtsgl");
            String xxtskcqdTableName = getBizObjectFacade().getTableName("xxtskcqd");
            selectSql.append("select count(*) from " + xxtsglTableName + " A, " + xxtskcqdTableName + " B where A.id = B.parentId and A.id in ");
            selectSql.append(idListSql);
            selectSql.append(" and B.kcbh = '" + courseId + "' and A.hdjzrq >= CURDATE() and zt = '已启动'");
            log.info("selectSql:{}", selectSql);
            BigInteger bigInteger = (BigInteger) entityManager.createNativeQuery(selectSql.toString()).unwrap(NativeQueryImpl.class).getSingleResult();
            int i0 = bigInteger.compareTo(new BigInteger("0"));
            preview = i0 > 0 ? true : false;
        }
//#############################################

        return getOkResponseResult(preview, "success");
    }

    @GetMapping("learnPreview")
    @Transactional
    public ResponseResult<String> learnPreview(@RequestParam String courseId, @RequestParam String msg) {

        String tableName = getBizObjectFacade().getTableName("kcqd");
        StringBuilder selectCourseInfo = new StringBuilder("SELECT * FROM `" + tableName + "` T WHERE T.id = '" + courseId + "';");
        List<Map<String, Object>> courseInfo = entityManager.createNativeQuery(selectCourseInfo.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
        String kcbh1 = MapUtils.getString(courseInfo.get(0), "kcbh");
        String userId = getUserId();
        StringBuilder selectsqkcsql = new StringBuilder();
        selectsqkcsql.append("select * from iwrwy_sqkkxq where creater='" + userId + "' and kcbh='" + kcbh1 + "'");
        List<Map<String, Object>> courseInfo2 = entityManager.createNativeQuery(selectsqkcsql.toString()).unwrap(NativeQueryImpl.class).
                setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
        if (CollectionUtils.isNotEmpty(courseInfo2)) {
            return getErrResponseResult("当前人员已发起过申请,请勿重复申请", 500L, "当前人员已发起过申请,请勿重复申请");
        }

        UserModel user = getOrganizationFacade().getUser(userId);
        int index = user.getUnitType().getIndex();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();

        // 调用产品获取所属组织方法
        UserHelper userHelper = new UserHelper(dubboConfigService, getMainCorpId());
        ResponseResult<List<UserManagerVO>> listResponseResult = userHelper.listManagerConfig(userId);
        List<UserManagerVO> data = listResponseResult.getData();
        Map<String, Object> map = new HashMap<>();
        for (UserManagerVO datum : data) {
            // 主组织
            if (datum.getIsMainDept()) {
                ItemInfo sqrN = new ItemInfo();
                sqrN.setId(datum.getUserId());
                sqrN.setType(index);
                sqrN.setName(datum.getUserName());
                JSONArray sqrNjsonArray = JSONArray.fromObject(sqrN);
                map.put("sqrN", sqrNjsonArray.toString());
                ItemInfo sqrzbmN = new ItemInfo();
                sqrzbmN.setId(datum.getDept().get(0).getId());
                sqrzbmN.setType(datum.getDept().get(0).getUnitType());
                sqrzbmN.setName(datum.getDept().get(0).getName());
                JSONArray sqrzbmNjsonArray = JSONArray.fromObject(sqrzbmN);
                map.put("sqrzbmN", sqrzbmNjsonArray.toString());
                map.put("sqsj", df.format(calendar.getTime()));
                map.put("kcbh", courseInfo.get(0).get("kcbh"));
                map.put("sqrly", msg);
                break;
            }
        }
        // 申请开课详情表单保存
        BizObjectCreatedModel courseWant = new BizObjectCreatedModel("sqkkxq", map, false);
        courseWant.setSequenceStatus(SequenceStatus.COMPLETED.name());
        String bizObjectId = getBizObjectFacade().saveBizObject(userId, courseWant, false);
        log.info("\n=======申请开课详情表单保存成功,bizObjectId={}", bizObjectId);

        String sqkkxqTable = getBizObjectFacade().getTableName("sqkkxq");
        StringBuilder count = new StringBuilder("SELECT COUNT(T.id) FROM `" + sqkkxqTable + "` T WHERE T.kcbh = '" + courseInfo.get(0).get("kcbh") + "';");
        BigInteger countsqkkxqNum = (BigInteger) entityManager.createNativeQuery(count.toString()).getSingleResult();
        String wykkTable = getBizObjectFacade().getTableName("wykk");
        StringBuilder countwykksql = new StringBuilder("SELECT COUNT(T.id) FROM `" + wykkTable + "` T WHERE T.kcbh = '" + courseInfo.get(0).get("kcbh") + "'");
        BigInteger countwykksqlNum = (BigInteger) entityManager.createNativeQuery(countwykksql.toString()).getSingleResult();
        if (countwykksqlNum.intValue() == 0) {
            // 申请开课表单保存
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("kcbh", courseInfo.get(0).get("kcbh"));
            paramMap.put("kcmc", courseInfo.get(0).get("courseName"));
            paramMap.put("kcjj", courseInfo.get(0).get("LongText1639381733243"));
            paramMap.put("sqrs", countsqkkxqNum);
            BizObjectCreatedModel courseWantCount = new BizObjectCreatedModel("wykk", paramMap, false);
            courseWantCount.setSequenceStatus(SequenceStatus.COMPLETED.name());
            String courseWantCountId = getBizObjectFacade().saveBizObject(userId, courseWantCount, false);
            log.info("\n=======申请开课表单保存成功,bizObjectId={}", courseWantCountId);
        } else {
            // 申请开课次数更新
            StringBuilder updateCount = new StringBuilder("UPDATE `" + wykkTable + "` T SET T.sqrs = '" + countsqkkxqNum + "' WHERE T.kcbh = '" + courseInfo.get(0).get("kcbh") + "'");
            int updateNum = entityManager.createNativeQuery(updateCount.toString()).executeUpdate();
            if (updateNum != 0) {
                log.info("\n=======申请开课次数记录成功,instanceId={}", updateNum);
            }
        }
        String kcbh = (String) courseInfo.get(0).get("kcbh");
        StringBuilder sql = new StringBuilder();
        sql.append("select * from iwrwy_spkkcx where kcbh='").append(kcbh).append("'");
        List<Map<String, Object>> kkcx = entityManager.createNativeQuery(sql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
        if (CollectionUtils.isEmpty(kkcx)) {
            BizObjectCreatedModel bizObjectCreatedModel = new BizObjectCreatedModel();
            bizObjectCreatedModel.setSchemaCode("spkkcx");
            bizObjectCreatedModel.put("kcbh", kcbh);
            bizObjectCreatedModel.put("kcmc", courseInfo.get(0).get("courseName"));
            bizObjectCreatedModel.put("kcjj", courseInfo.get(0).get("LongText1639381733243"));
            StringBuilder countsqrs = new StringBuilder();
            countsqrs.append("select  sqrs from iwrwy_wykk where kcbh='").append(kcbh).append("'");
            List<Map<String, Object>> countlist = entityManager.createNativeQuery(countsqrs.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
            bizObjectCreatedModel.put("sqrs", countlist.get(0).get("sqrs"));
            List<Map<String, Object>> zb = new ArrayList<>();
            Map<String, Object> zbmap = new HashMap<>();
            SelectionValue selectionValue = new SelectionValue();
            selectionValue.setId(getUserId());
            selectionValue.setType(UnitType.USER);
            zbmap.put("sqr", Collections.singletonList(selectionValue));
            StringBuilder selectsql = new StringBuilder();
            selectsql.append("SELECT deptId FROM `h_org_dept_user` where userId='").append(getUserId()).append("' and main=1 ");
            List<Map<String, Object>> selectlist = entityManager.createNativeQuery(selectsql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
            SelectionValue bm = new SelectionValue();
            bm.setId((String) selectlist.get(0).get("deptId"));
            bm.setType(UnitType.DEPARTMENT);
            zbmap.put("sqrbm", Collections.singletonList(bm));
            zbmap.put("sqsj", new Date());
            zbmap.put("rowStatus", "Added");
            zb.add(zbmap);
            bizObjectCreatedModel.put("kkcxzb", zb);
            getBizObjectFacade().saveBizObject(getUserId(), bizObjectCreatedModel, false);
        } else {
            String id = (String) kkcx.get(0).get("id");
            BizObjectCreatedModel biz = new BizObjectCreatedModel();
            biz.setId(id);
            biz.setSchemaCode("spkkcx");
            StringBuilder countsqrs = new StringBuilder();
            countsqrs.append("select  sqrs from iwrwy_wykk where kcbh='").append(kcbh).append("'");
            List<Map<String, Object>> countlist = entityManager.createNativeQuery(countsqrs.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
            biz.put("sqrs", countlist.get(0).get("sqrs"));
            List<Map<String, Object>> zb = new ArrayList<>();
            Map<String, Object> zbmap = new HashMap<>();
            SelectionValue selectionValue = new SelectionValue();
            selectionValue.setId(getUserId());
            selectionValue.setType(UnitType.USER);
            zbmap.put("sqr", Collections.singletonList(selectionValue));
            StringBuilder selectsql = new StringBuilder();
            selectsql.append("SELECT deptId FROM `h_org_dept_user` where userId='").append(getUserId()).append("' and main=1 ");
            List<Map<String, Object>> selectlist = entityManager.createNativeQuery(selectsql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
            SelectionValue bm = new SelectionValue();
            bm.setId((String) selectlist.get(0).get("deptId"));
            bm.setType(UnitType.DEPARTMENT);
            zbmap.put("sqrbm", Collections.singletonList(bm));
            zbmap.put("sqsj", new Date());
            zbmap.put("rowStatus", "Added");
            zb.add(zbmap);
            biz.put("kkcxzb", zb);
            getBizObjectFacade().saveBizObject(getUserId(), biz, false);
        }

        return getOkResponseResult(bizObjectId, "success");
    }

    /**
     * 讲师手册权限
     */
    @GetMapping("/instructorManualAuthority")
    public ResponseResult instructorManualAuthority(@RequestParam String courseId) {
        boolean flag = false;
        String userId = getUserId();
        //直接去查申请表
        String tableName = getBizObjectFacade().getTableName("jsscsq");
        StringBuilder sql = new StringBuilder();
        sql.append("select * from ").append(tableName)
                .append(" where creater='").append(userId).append("' and kcbh='")
                .append(courseId).append("' and sequenceStatus='COMPLETED'  and pfzt='同意' ");
        List<Map<String, Object>> selectlist = entityManager.createNativeQuery(sql.toString()).
                unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
        if (CollectionUtils.isEmpty(selectlist)) {
            return getOkResponseResult(flag, "暂无讲师手册权限");
        } else {
            return getOkResponseResult(!flag, "success");
        }
    }

    /**
     * 讲师手册申请
     */
    @GetMapping("/instructorManualApplication")
    public ResponseResult instructorManualApplication(@RequestParam String courseId) {
        //判断是否发起过申请
        String userId = getUserId();
        UserModel user = getOrganizationFacade().getUser(userId);
        String tableName = getBizObjectFacade().getTableName("jsscsq");
        //获取课程信息
        StringBuilder selectSql = new StringBuilder();
        String kcqdTableName = getBizObjectFacade().getTableName("kcqd");
        selectSql.append("select courseName,kcbh from ").append(kcqdTableName).append(" where id='").append(courseId).append("'");
        List<Map<String, Object>> resultList = entityManager.createNativeQuery(selectSql.toString()).
                unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
        String courseName = (String) resultList.get(0).get("courseName");
        String kcbh = (String) resultList.get(0).get("kcbh");

        //申请信息
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT sequenceStatus,pfzt FROM ")
                .append(tableName).append(" where creater ='").append(userId).append("' and kcbh='").append(courseId).append("'");
        List<Map<String, Object>> sqllist = entityManager.createNativeQuery(sql.toString()).
                unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
        if (CollectionUtils.isEmpty(sqllist)) {
            Map<String, Object> map = new HashMap<>();
            map.put("coursename", courseName);
            map.put("kcbh", courseId);
            BizObjectCreatedModel departmentLeaderApproval = new BizObjectCreatedModel("jsscsq", map, false);
            String bizObjectId = getBizObjectFacade().saveBizObject(userId, departmentLeaderApproval, false);
            String instanceId = getWorkflowInstanceFacade().startWorkflowInstance(user.getDepartmentId(), userId, "jsscsqProcess", bizObjectId, true);

        } else {
            String sequenceStatus = (String) sqllist.get(0).get("sequenceStatus");
            String pfzt = (String) sqllist.get(0).get("pfzt");
            if ("PROCESSING".equals(sequenceStatus)) {
                return getErrResponseResult(-1L, "预览申请流程审批中，请勿重复申请");
            }

            if ("COMPLETED".equals(sequenceStatus) && "不同意".equals(pfzt)) {
                Map<String, Object> map = new HashMap<>();
                map.put("coursename", courseName);
                map.put("kcbh", courseId);
                BizObjectCreatedModel departmentLeaderApproval = new BizObjectCreatedModel("jsscsq", map, false);
                String bizObjectId = getBizObjectFacade().saveBizObject(userId, departmentLeaderApproval, false);
                String instanceId = getWorkflowInstanceFacade().startWorkflowInstance(user.getDepartmentId(), userId, "jsscsqProcess", bizObjectId, true);
                return getOkResponseResult("发起讲师申请预览成功");
            }
        }
        return getOkResponseResult("发起讲师申请预览成功");
    }
}
